<script setup>
import {BaseURL, Version} from "../../utils/lshttp";
import {useSetting} from "./use_setting";
import {toMiniAppSetting} from "../../utils/utils";
import {ref} from "vue";
import {updateNicknameAndAvatarAPI} from "../../services/me";
import {onShow} from "@dcloudio/uni-app";
import {requestAndroidPermission} from "../../js_sdk/wa-permission/permission";

const {
  user,
  show,
  Loingshow,
  zhuxiaoshow,
  parent_id,
  version,
  phonePop,
  inPutTemCode,
  tel,
  temCode,
  checked,
  userInfoStore,
  close,
  changeis,
  checkUpdate,
  submitTel,
  changeMTTel,
  submitTemCode,
  exitConfirm,
  outCountConfirm,
  handleChangeLoginPassword,
} = useSetting()

// 提交的用户昵称和用户头像
const nickname = ref('')
const avatar = ref('')

onShow(async () => {
  getUserInfo()
})

const getUserInfo = () => {
  user.value = userInfoStore.userInfo
  nickname.value = user.value?.nickname
  avatar.value = user.value?.avatar
  tel.value = user.value?.mt_phone
  parent_id.value = user.value?.parent_id
}


// 更新头像地址
const handleUpdateNicknameAndAvatar = async (path) => {
  avatar.value = path
  await updateNicknameAndAvatarAPI({nickname: nickname.value, avatar: path})
  await userInfoStore.getUserInfo()
  getUserInfo()
}
// 确定修改昵称
const handleChangeNickname = async () => {
  await updateNicknameAndAvatarAPI({nickname: nickname.value, avatar: avatar.value})
  await userInfoStore.getUserInfo()
  getUserInfo()
  show.value = false
}

// 上传图片
const uploadMyImg = () => {
  uni.chooseImage({
    count: 1,
    // 默认9
    sizeType: ['original', 'compressed'],
    // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'],
    // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      const tempFilePaths = res.tempFilePaths;
      uni.showLoading({
        title: '上传中'
      })
      uni.uploadFile({
        url: BaseURL + '/api/user/uploadAvatar',
        method: 'POST',
        filePath: tempFilePaths[0],
        name: 'file',
        success(res) {
          uni.hideLoading()
          let data = JSON.parse(res.data)
          if (data.status !== 1) {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
            return
          }
          setTimeout(()=>{
            handleUpdateNicknameAndAvatar(data.result.show_path)
          },200)
        },
        fail(error) {
          uni.hideLoading()
          uni.showToast({title: JSON.parse(error) + "", icon: 'none', duration: 2000})
        }
      })
    }
  });
}
// 获取权限
const getPermission = async () => {
  let platform = uni.getSystemInfoSync().platform
  if (platform === 'ios') {
    uploadMyImg()
    return
  }

  const photo = uni.getStorageSync("photo")
  if (photo) {
    uploadMyImg()
    return
  }
  uni.showModal({
    title: '提示',
    content: "修改头像需要获取您设备上的相册权限，是否同意授权？",
    confirmText: '同意授权',
    success: async function (res) {
      if (res.confirm) {
        const result = await requestAndroidPermission("android.permission.READ_EXTERNAL_STORAGE")
        if (result === 1) {
          uni.setStorageSync("photo", true)
          uploadMyImg()
        } else if (result === 0) {
          uni.setStorageSync('photo', false)
        } else {
          uni.setStorageSync('photo', false)
        }
      }
    }
  })
}
// 上传头像
const onChooseAvatar = async (e) => {
  const avatarUrl = e.detail.avatarUrl
  console.log("avatarUrl", avatarUrl)
  uni.uploadFile({
    url: BaseURL + '/api/user/uploadAvatar',
    method: 'POST',
    filePath: avatarUrl,
    name: 'file',
    success(res1) {
      uni.hideLoading()
      let data = JSON.parse(res1.data)
      if (data.status !== 1) {
        uni.showToast({
          title: res1.msg,
          icon: 'none'
        })
        return
      }
      handleUpdateNicknameAndAvatar(data.result.show_path)
    }
  })
}
// 查看美团绑定手机号
const toMTSetting = () => {
  toMiniAppSetting(1)
}
</script>

<template>
  <view>
    <up-navbar
        title="设置"
        placeholder
        titleStyle="color:black"
        leftIconColor="#000"
        auto-back
        bgColor="#FDE52F"
    >
    </up-navbar>

    <view class="list-wrap">
      <view class="list-box">
        <view class="liest-box">
          <view class="head-titel">头像</view>
          <!-- #ifdef MP -->
          <button class="right-jiao avatar-wrapper up-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
            <image class="avatar" :src="user?.avatar"></image>
            <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
          </button>
          <!--#endif-->
          <!-- #ifdef APP-PLUS -->
          <view class="right-jiao avatar-wrapper" @click="getPermission">
            <image class="avatar" :src="user?.avatar"></image>
            <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
          </view>
          <!--#endif-->
          <!-- #ifdef H5-->
          <view class="right-jiao avatar-wrapper" @click="uploadMyImg">
            <image class="avatar" :src="user?.avatar"></image>
            <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
          </view>
          <!--#endif-->
        </view>
      </view>
      <view class="list-box">
        <view class="liest-box">
          <view>修改昵称</view>
          <view class="right-jiao" @click="show=true">
            <text>{{ user?.nickname }}</text>
            <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
          </view>
        </view>
      </view>
      <view class="list-box">
        <view class="liest-box">
          <!--<view><u-icon name="order" color="#333" size="48"></u-icon></view>-->
          <view>手机号</view>
          <view class="right-jiao" @click="handleChangeLoginPassword(3)">
            <text>{{ user?.username.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2") || '点击绑定' }}</text>
            <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
          </view>
        </view>
      </view>
      <view class="list-box">
        <view class="liest-box">
          <!--<view><u-icon name="order" color="#333" size="48"></u-icon></view>-->
          <view>关联美团账号</view>
          <view class="right-jiao" @click="changeMTTel">
            <text>{{ tel?.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2") || '立即绑定' }}</text>
            <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
          </view>
        </view>
      </view>
      <view class="list-box">
        <view class="liest-box">
          <!--<view><u-icon name="order" color="#333" size="48"></u-icon></view>-->
          <view>填写邀请码入团</view>
          <view class="right-jiao" @click="parent_id === 0?inPutTemCode = true:inPutTemCode = false">
            <text>{{ parent_id === 0 ? '立即填写' : '已绑定' }}</text>
            <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
          </view>
        </view>
      </view>
      <view class="list-box">
        <view class="liest-box">
          <!--<view><u-icon name="order" color="#333" size="48"></u-icon></view>-->
          <view>登录密码</view>
          <view class="right-jiao" @click="handleChangeLoginPassword(1)">
            <text>修改</text>
            <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
          </view>
        </view>
      </view>
      <navigator class="liest-box" url="/pages/login/ysxy" hover-class="none">
        <view class="list-box">
          <view>隐私协议</view>
          <view class="right-jiao">
            <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
          </view>
        </view>
      </navigator>
      <navigator class="liest-box" url="/pages/login/yhxy" hover-class="none">
        <view class="list-box">
          <view>用户协议</view>
          <view class="right-jiao">
            <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
          </view>
        </view>
      </navigator>
      <view class="list-box">
        <view>个性化推送</view>
        <view class="right-jiao">
          <view style="height: 24px;">
            <up-switch v-model="checked" size="20" activeColor="#FC754A" @change="changeis"></up-switch>
          </view>
        </view>
      </view>
      <view class="list-box" @click="zhuxiaoshow = true">
        <!--<view><u-icon name="edit-pen" color="#333" size="48"></u-icon></view>-->
        <view>注销账号</view>
        <view class="right-jiao">
          <up-icon name="arrow-right" color="#dadada" size="18"></up-icon>
        </view>
      </view>
    </view>
    <view style="height: 30rpx"></view>
    <view class="Position">
      <view @click="Loingshow = true">退出登录</view>
    </view>

    <!-- #ifdef MP-WEIXIN || H5-->
    <view class="version">当前版本：{{ Version }}</view>
    <!-- #endif -->
    <!-- #ifdef APP-PLUS -->
    <view class="version" @click="checkUpdate">当前版本：{{ version }}</view>
    <!-- #endif -->
    <view style="height: 530rpx;">

    </view>
    <up-modal :show="Loingshow" title="温馨提示" content="您确定要退出登陆吗？退出后无法享受本程序的任何服务!"
              :showCancelButton="true" @confirm="exitConfirm" @cancel="Loingshow = false"></up-modal>

    <up-modal :show="zhuxiaoshow" title="温馨提示"
              content="请确认您的账号中是否存在（如可提余额、推广收益等），请提现操作完成后再注销账户。否则一切后果自己承担!"
              :showCancelButton="true" @confirm="outCountConfirm" @cancel="zhuxiaoshow = false"></up-modal>

    <up-popup :show="show" mode="center" round="10" :closeable="true" @close="show = false">
      <view class="change_box">
        <view class="pay_type">修改昵称</view>
        <up-input v-model="nickname" border="none"
                  class="inputWidth"
                  clearable
                  :customStyle="{background:'#F6F6F6','border-radius': 0,padding:'10rpx 20rpx'}"
                  placeholder="请输入昵称"/>
        <view class="ok_btn" @click="handleChangeNickname()">
          确定修改
        </view>
      </view>
    </up-popup>
    <up-popup :show="phonePop" mode="center" :safeAreaInsetBottom="false" round="10" @close="close">
      <view class="wm_box">
        <view class="content_boxs">
          <view class="know_t">修改美团账号手机号</view>
          <view class="desc_text">
            <text style="color: #FF3E00;font-size: 26rpx">新手机号需与美团绑定手机号一致</text>
          </view>
          <view style="margin-left: 30rpx;margin-top: 10rpx;font-size: 28rpx">手机号</view>
          <view class="input_name">
            <up-input border="none"
                      class="inputWidth"
                      type="number"
                      clearable
                      :customStyle="{background:'#F6F6F6','border-radius': 0,padding:'10rpx 20rpx'}"
                      placeholder="请输入手机号" v-model="tel"/>
          </view>
          <view class="tip" style="position: relative">
            <!-- #ifdef H5 -->
            <wx-open-launch-weapp id="launch-btn"
                                  username="gh_870576f3c6f9" path="mt/pages/setting/setting.html"
                                  style="position: absolute;z-index: 2;left: 0;width: 100%;height:100%;opacity: 0.01;background-color: #ff531a">
              <component :is="'script'" type='text/wxtag-template' style="display: block;">
                <div style="position: absolute;top: 0; left: 0; width: 100%;height: 100% ; opacity: 0"></div>
              </component>
            </wx-open-launch-weapp>
            <!-- #endif -->
            <text>您也可以前往我的-设置-关联美团手机号进行修改。</text>
            <text style="color: #ff7400;" @click="toMTSetting">点击查看美团绑定的手机号</text>
          </view>
          <view class="btns_con">
            <view style="flex: 1"></view>
            <button class="zbbm" @click="close">取消修改</button>
            <button class="submit" @click="submitTel">确认修改</button>
          </view>
        </view>
      </view>
    </up-popup>
    <up-popup :show="inPutTemCode" mode="center" :safeAreaInsetBottom="false" round="10" @close="close">
      <view class="wm_box">
        <view class="content_boxs">
          <view class="know_t">填写邀请码</view>
          <view style="margin-left: 30rpx;margin-top: 30rpx;font-size: 28rpx">邀请码</view>
          <view class="input_name" style="margin-bottom: 0">
            <up-input border="none"
                      class="inputWidth"
                      clearable
                      :customStyle="{background:'#F6F6F6','border-radius': 0,padding:'10rpx 20rpx'}"
                      placeholder="请输入邀请码" v-model="temCode"/>
          </view>
          <view class="desc_text" style="padding-bottom: 10rpx;padding-top: 20rpx;display: flex">
            <view style="flex: 1"></view>
            <text style="color: #FF3E00;font-size: 26rpx">填写邀请码才能入团</text>
          </view>
          <view class="btns_con">
            <view style="flex: 1"></view>
            <button class="zbbm" @click="close">取消</button>
            <button class="submit" @click="submitTemCode">确认填写</button>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>
<style>
page {
  background-color: #F6F6F6;
}
</style>
<style lang="scss" scoped>
.up-button:after {
  border: none;
}

.u-status-bar,
.u-navbar__content {
  background-image: linear-gradient(90deg, #FDE52F, #FDE52F);
}

.head-titel {
  flex: 1;
}

.version {
  width: 100%;
  font-size: 26rpx;
  color: #a6a6a6;
  text-align: center;
  margin-top: 60rpx;
}

.avatar-wrapper {
  padding: 0;
  background: #FFFFFF;
}

.change_box {
  box-sizing: border-box;
  padding: 40rpx;
  width: 560rpx;

  .pay_type {
    font-size: 28rpx;
    color: #333;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20rpx;
  }

  .input_name {
    border-bottom: 1px solid #eee;
    width: 100%;
  }
}

.Position {
  margin: 38rpx auto;
  width: 568rpx;
  font-size: 30rpx;
  background: linear-gradient(to right, #eaeaea, #eaeaea);
  border-radius: 200rpx;
  padding: 25rpx 36rpx;
  text-align: center;
  color: #666666;
}

.ok_btn {
  width: 90%;
  font-size: 30rpx;
  margin: 40rpx auto 0;
  background: linear-gradient(to right, #FC754A, #FEBC5B);
  border-radius: 200rpx;
  padding: 20rpx 36rpx;
  text-align: center;
  color: #ffffff;
}

.list-wrap {
  .list-box {
    padding: 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    margin-bottom: 20rpx;

    .liest-box {
      display: flex;
      align-items: center;
      width: 100%;
    }

    .right-jiao {
      margin-left: auto;
      display: flex;
      align-items: center;

      image {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
      }
    }
  }
}

.wm_box {
  position: relative;
  width: 600rpx;
  background: #ffffff;
  border-radius: 32.5rpx;
  margin: -186rpx auto 0;
}

.content_boxs {
  box-sizing: border-box;
  position: relative;

  .know_t {
    font-size: 32rpx;
    color: #000;
    text-align: center;
    box-sizing: border-box;
    padding: 20rpx;
    border-bottom: 1px solid #eee;
  }

  .btns_box {
    width: 280rpx;
    height: 64rpx;
    background: linear-gradient(270deg, #FEB85A 0%, #FC754A 100%);
    border-radius: 50rpx;
    font-size: 28rpx;
    color: #fff;
    line-height: 64rpx;
    text-align: center;
  }
}

.desc_text {
  box-sizing: border-box;
  padding: 30rpx 30rpx 0;
  font-size: 30rpx;
  color: #AAAAAA;
  line-height: 56rpx;
  text-align: left;

  text {
    color: #F97632;
    text-align: left;
  }
}

.content_boxs {
  box-sizing: border-box;
  position: relative;

  .know_t {
    font-size: 32rpx;
    color: #000;
    font-weight: bold;
    text-align: center;
    box-sizing: border-box;
    margin-top: 6rpx;
    padding: 20rpx;
    border-bottom: 1px solid #eee;
  }

  .desc_text {
    font-size: 22rpx;
    line-height: 36rpx;
  }

  .tip {
    color: #BFBFBF;
    font-size: 24rpx;
    line-height: 36rpx;
    margin: 0 30rpx;
  }

  .input_name {
    margin: 20rpx 30rpx;
  }

  .btns_box {
    width: 280rpx;
    height: 64rpx;
    background: linear-gradient(270deg, #FEB85A 0%, #FC754A 100%);
    border-radius: 50rpx;
    font-size: 28rpx;
    color: #fff;
    line-height: 64rpx;
    text-align: center;
  }

  .btns_con {
    display: flex;
    justify-content: flex-end;
    font-size: 26rpx;
    margin: 20rpx 30rpx 30rpx;

    button {
      margin-left: 30rpx;
      font-size: 24rpx;
    }

    .zbbm {
      border-radius: 200rpx;
      width: 176rpx;
      background-color: #FFFFFF;
      border: #DDDDDD 1rpx solid;
      color: #999999;
    }

    .submit {
      border-radius: 200rpx;
      width: 176rpx;
      background: linear-gradient(131deg, #FC754A 0%, #FC754A 0%, #FEB95A 100%);
      color: #FFFFFF;
    }
  }
}
</style>
